//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.user;

import java.util.*;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.Globals;
import org.apache.commons.beanutils.PropertyUtils;

import com.broadvision.data.common.DataConstants;
import com.broadvision.portal.services.util.TransferBeanUtils;
import com.broadvision.portal.services.UserTemplate;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.manage.common.tools.user.UserProfile;
import com.broadvision.web.servlet.SessionVisitor;
import com.broadvision.system.accesscontrol.client.*;
import com.broadvision.visitor.client.VisitorManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.portal.services.*;
import com.broadvision.web.action.Tab;
import com.broadvision.license2.LicUtil;
import com.broadvision.lictool2.LicToolWebApp;

import com.broadvision.manage.tools.action.BaseAction;
import com.broadvision.visitor.client.VisitorGroupManager;
import com.broadvision.visitor.interfaces.VisitorGroup;

/**
 * Implements the Action for editing a user.
 */
public class ProfileEditAction extends BaseAction {

  public static final String VIEW_BEAN_NAME = "mtUserEditView";
  public static final String PAGE_TAB = "pagetab";
  public static final int  MAX_NUMBER_OF_GROUPS = 2147483646;
  /**
   * Implements the action for editing a user.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
				      ActionForm form,
				      HttpServletRequest request,
				      HttpServletResponse response)
    throws Exception
  {
    try {
      PortalVisitor agent = getPortalVisitor(request);
      Visitor visitor = agent.getVisitor();

      long profileId = UserProfile.UNDEFINED_USER_ID;
      String parameter = request.getParameter("userId");
      if (null != parameter && parameter.length() > 0) {
        profileId = Long.parseLong(parameter);
      }
 
      if (!UserProfile.isPermitted(visitor, "Edit") && (profileId != visitor.getId()) && (!UserProfile.isOrganizationAdmin(visitor))) {
	  request.setAttribute(Globals.ERROR_KEY, "error.user.profile.no.edit");
	  return mapping.findForward("failure");
      }

      Tab tab = (Tab)request.getAttribute(PAGE_TAB);
      if (tab != null) {
	tab.disable();
      }    

      long userId = UserProfile.UNDEFINED_USER_ID;
      String visitorId = null;
      String myProfile = request.getParameter("myProfile");
      
      if ("true".equals(myProfile)) {
	userId = visitor.getId();
      }
      else {
	visitorId = request.getParameter("userId");
	Long undefinedUserId = new Long(UserProfile.UNDEFINED_USER_ID);
	if (visitorId == null || visitorId.length() == 0 ||
	  undefinedUserId.toString().equals(visitorId)) {
	  visitorId = (String) request.getAttribute("userId");
	}
	
	if (visitorId != null && visitorId.length() > 0) {	
	  userId = Long.parseLong(visitorId);
	}
      }

     // obtain all the related organization group assoicated to the visitor
     boolean hasUserAdminRole = isUserInRole(visitor, UserProfile.USER_ADMIN);
	 boolean hasOrganizationAdminRole = UserProfile.isOrganizationAdmin(visitor);
     if(!hasUserAdminRole && !hasOrganizationAdminRole && profileId != visitor.getId()){
	   request.setAttribute(Globals.ERROR_KEY, "error.group.noGroupAdmin");
	   return mapping.findForward("failure");
	 }
	 if (hasUserAdminRole == false && profileId != visitor.getId()) {
     HashMap orgAdminsMap = new HashMap();
     
        AccessManager accessMgr = AccessManager.instance();
        List orgAdmins = accessMgr.getOwnerObjectsForPrincipal((Principal)visitor, UserProfile.ORGANIZATION_ADMIN);
        if (null != orgAdmins) {
           for (int j = 0; j < orgAdmins.size(); j++) {
           ACObjectID ac = (ACObjectID) orgAdmins.get(j);
           orgAdminsMap.put(ac.getObjectID().trim(), ac);
           }
        }
     	 
	 // obtain all the assoicated group to the user, obtained all the necessary path that associated to the 
	 // organization related.
	 VisitorGroup[] groups = VisitorGroupManager.findAllGroupsVisitorBelongsTo(profileId, MAX_NUMBER_OF_GROUPS);
     boolean doFQN = false;
	 if (null != groups) {
       for (int i = 0; i < groups.length; i++) {
    	 if(doFQN == true)
	        break;
         VisitorGroup group = groups[i];
         List parents = new ArrayList(1);
         parents.add(group);
         parents.addAll(group.getParents(true));
         for (int j = 0; parents != null && j < parents.size(); j++) {
             VisitorGroup parent = (VisitorGroup)parents.get(j);
             if (orgAdminsMap.containsKey(parent.getFullyQualifiedName())) {
                doFQN = true;
                break;
             }
         }
       }
     }
	 // visitor is not userAdmin, user is not equal to visitor id, visitor doesn't
	 // have any member under his/her organization group
	 if ( !doFQN ) {
	   request.setAttribute(Globals.ERROR_KEY, "error.group.noGroupAdmin");
	   return mapping.findForward("failure");
     }
	 }
      UserUtils.setP(form, "userId", new Long(userId));

      UserProfile userProfile = new UserProfile(userId);
      userProfile.edit();
      
      TransferBeanUtils.copyPropertiesToView(form, userProfile);
      TransferBeanUtils.copyPropertiesToView(form, userProfile.getDynaBean());

      PortalVisitor user = new PortalVisitor(userId, agent);
      user.setServiceId(getServiceId(request));
      
      UserUtils.setP(form, "epUserTmplId", new Long(-1));
      UserUtils.setP(form, "epEmailAlert", Boolean.FALSE);

      try {
	VisitorUserTemplate vUT = user.getVisitorUserTemplate();
	if (null != vUT) {
	  UserTemplate ut = vUT.getUserTemplate();
	  if (null != ut) {
	    UserUtils.setP(form, "epUserTmplId", new Long(ut.getId()));
	  }
	}
	UserUtils.setP(form, "epEmailAlert", new Boolean(user.isEmailAlertEnabled()));
      }
      catch (Exception pNIS) {
	// no need to do anything. the templateId has been set to -1 in this case
      }

      // prepare bean view

      ViewDynaBean view = new ViewDynaBean(VIEW_BEAN_NAME, mapping);
      request.setAttribute(VIEW_BEAN_NAME, view);

      // grab the list of user templates: a temporary solution before the pop-up page is ready
      List userTemplateList = UserTemplate.getUserTemplates (getServiceId(request),
							     DataConstants.BV_ONLINE_DB_CONTENT,
							     0,
							     getPortalVisitor(request));
      
      UserUtils.setP(view, "userTemplateList", userTemplateList);
      
      //
      UserUtils.setP(view, "userDataList", VisitorDataUtilities.getUserListData());
      UserUtils.setP(view, "userTypeList", VisitorDataUtilities.getUserTypesData());
      UserUtils.setP(view, "corporateStatusList", VisitorDataUtilities.getCorporateUserStatusData());
      //
      
      TransferBeanUtils.copyPropertiesToView(view, userProfile);
      
      UserUtils.setP(view, "useFullName", new Boolean(!VisitorManager.isUsingFMLName()));

      String formattedName = UserUtils.getFormattedName(userProfile.getVisitor(), 
							getResources(request),
							getLocale(request));
      UserUtils.setP(view, "formattedName", formattedName);

      int retcode =  LicToolWebApp.getInstance().checkTag("portal.framework.basic");
      UserUtils.setP(view, "showUserTemplate", new Boolean((retcode >= 0)));
      UserUtils.setP(view, "showUserGroup", new Boolean((retcode >= 0)));
      UserUtils.setP(view, "isUserAdmin", new Boolean(isUserInRole(visitor, "UserAdmin")));

      UserUtils.setP(view, "editable", UserProfile.isPermitted(visitor, "Edit") ? Boolean.TRUE : Boolean.FALSE);

	  
    }
    catch (Exception ex) {
	ex.printStackTrace();
	request.setAttribute(Globals.ERROR_KEY, "error.application");
	return mapping.findForward("failure");
    }

    return mapping.findForward("success");
  }
  /*************************************************************************************************/
  public void setLists(ArrayList listData){
	  
  
  }
  /*************************************************************************************************/
}//end class
